package com.sc.socket.udpgroup;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.UUID;

/**
 * @author shuc001
 * @Date 2019-02-02 23:26
 */
public class Provider {
    public static void main(String[] args) throws IOException {
        String sn = UUID.randomUUID().toString();
        ProviderThread pt = new ProviderThread(sn);
        pt.start();

        System.in.read();
        pt.exist();
        System.out.println("完成");
    }


    private static class ProviderThread extends Thread{

        private final String sn;
        private boolean done =false;
        private DatagramSocket ds = null;

        public ProviderThread(String sn) {
            this.sn = sn;
        }

        @Override
        public void run() {
            try {
                ds = new DatagramSocket(20000);
                while (!done){
                    final byte[] buf = new byte[512];
                    DatagramPacket recieve =  new DatagramPacket(buf,buf.length);
                    ds.receive(recieve);
                    String data =  new String(recieve.getData(),0,recieve.getLength());
                    System.out.println("20000收到消息: "+data);

                    int port = MessageCreator.parseCode(data);
                    if(port!=-1) {
                        String resp =  MessageCreator.buildWithSN(sn);
                        byte[] respBytes = resp.getBytes();
                        DatagramPacket packet = new DatagramPacket(respBytes,
                                respBytes.length,recieve.getAddress(),port);
                        ds.send(packet);
                        System.out.println("发送");
                    }

                }
            }catch (Exception e) {
            }finally {
                close();
            }
        }

        private void close(){
            if(ds!=null){
                ds.close();
                ds=null;
            }

        }

        private void exist(){
            done=true;
            close();
        }
    }
}
